package com.zzyl.nursing.service.impl;

import java.util.List;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author srt
 * @date 2025-10-10
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    //新增入住信息  老人家属信息存到remark字段中
//新增入住配置
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int qpply(CheckInApplyDto dto) {
        //校验老人是否已入住  如果已入住直接抛异常BaseException
        //根据老人的身份证号 + 状态 从老人表中查询
        CheckInConfigDto configDto = dto.getCheckInConfigDto();
        CheckInElderDto elderDto = dto.getCheckInElderDto();
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();

        List<ElderFamilyDto> dtoList = dto.getElderFamilyDtoList();

        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, elderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus, 4);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (elder != null) {
            throw new BaseException("该老人已经入住");
        }
        //更新床位的状态
        Long bedId = configDto.getBedId();
        Bed bed = bedMapper.selectBedById(bedId);
        if (bed == null) {
            throw new BaseException("请选择正确床位");
        }
        bed.setBedStatus(1);
        bedMapper.updateById(bed);


        elder = saveOrUpdateElder(elderDto, bed);

        saveContract(checkInContractDto, elder, configDto);

        CheckIn checkIn = saveCheckIn(elder, configDto ,dtoList);
        saveCheckInConfig(  configDto,  checkIn);

        return 1;
    }

    private void saveCheckInConfig(CheckInConfigDto configDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setNursingLevelId(configDto.getNursingLevelId());
        checkInConfig.setNursingLevelName(configDto.getNursingLevelName());
        checkInConfig.setFeeStartDate(configDto.getFeeStartDate());
        checkInConfig.setFeeEndDate(configDto.getFeeEndDate());
        checkInConfig.setDeposit(configDto.getDeposit());
        checkInConfig.setNursingFee(configDto.getNursingFee());
        checkInConfig.setBedFee(configDto.getBedFee());
        checkInConfig.setInsurancePayment(configDto.getInsurancePayment());
        checkInConfig.setGovernmentSubsidy(configDto.getGovernmentSubsidy());
        checkInConfig.setOtherFees(configDto.getOtherFees());

        checkInConfigMapper.insert(checkInConfig);

    }

    private CheckIn saveCheckIn(Elder elder, CheckInConfigDto configDto , List<ElderFamilyDto> dtoList) {

        CheckIn checkIn = new CheckIn();

        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(configDto.getStartDate());
        checkIn.setEndDate(configDto.getEndDate());
        checkIn.setNursingLevelName(configDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());


        String jsonStr = JSONUtil.toJsonStr(dtoList);
        checkIn.setRemark(jsonStr);



        checkIn.setStatus(0);//（e：已入住，1：已退住）
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    //新增合同信息  合同号要求： HT+18位数字，例：HT202501011012590001
    private void saveContract(CheckInContractDto contractDto, Elder elder, CheckInConfigDto configDto) {
        Contract contract = new Contract();

        contract.setElderId(elder.getId());
        contract.setContractName(contractDto.getContractName());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setAgreementPath(contractDto.getAgreementPath());
        contract.setThirdPartyPhone(contractDto.getThirdPartyPhone());
        contract.setThirdPartyName(contractDto.getThirdPartyName());
        contract.setElderName(elder.getName());
        contract.setStartDate(configDto.getStartDate());
        contract.setEndDate(configDto.getEndDate());
        contract.setStatus(1);  // 状态 (0: 未生效, 1: 已生效, 2: 已过期, 3: 已失效)
        contract.setSignDate(contractDto.getSignDate());
        // contract.setTerminationSubmitter();
        // contract.setTerminationDate();
        // contract.setTerminationAgreementPath();
        contractMapper.insert(contract);
//        contract.setTerminationSubmitter();
//        contract.setTerminationDate();
//        contract.setTerminationAgreementPath();


    }

    //新增或更新老人elder
    private Elder saveOrUpdateElder(CheckInElderDto elderDto, Bed bed) {

        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, elderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (elder == null) {

            elder = new Elder();

            elder.setName(elderDto.getName());
            elder.setImage(elderDto.getImage());
            elder.setIdCardNo(elderDto.getIdCardNo());
            elder.setSex(elderDto.getSex());
            elder.setStatus(4);   //状态（0：禁用，1:启用  2:请假 3:退住中 4入住中 5已退住）
            elder.setPhone(elderDto.getPhone());
            elder.setBirthday(elderDto.getBirthday());
            elder.setAddress(elderDto.getAddress());
            elder.setIdCardNationalEmblemImg(elderDto.getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(elderDto.getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.insert(elder);

        } else {
            elder.setName(elderDto.getName());
            elder.setImage(elderDto.getImage());
            elder.setIdCardNo(elderDto.getIdCardNo());
            elder.setSex(elderDto.getSex());
            elder.setStatus(4);   //状态（0：禁用，1:启用  2:请假 3:退住中 4入住中 5已退住）
            elder.setPhone(elderDto.getPhone());
            elder.setBirthday(elderDto.getBirthday());
            elder.setAddress(elderDto.getAddress());
            elder.setIdCardNationalEmblemImg(elderDto.getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(elderDto.getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.updateById(elder);
            //elderMapper.updateElder();

        }
        return elder;
    }

}
